package com.zhang.util;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * User: 张
 * Date: 2024-11-20
 * Time: 9:39
 * Description:
 */
@Component
public class CommandRedisUtil {
    @Autowired
    private RedisUtil redisUtil;
    private final String redisName = "CommandList";
    private Map<String, String> post(){
        String jsonStr = (String) redisUtil.get(redisName);
        return JSON.parseObject(jsonStr, Map.class);
    }
    public void initCommandList(){
        Map<String, String> map = new HashMap<>();
        redisUtil.set(redisName, JSON.toJSONString(map));
        System.out.println("任务列表初始化");
    }

    public void addCommand(String ip, String executeId){
        Map<String, String> map = post();
        map.put(ip,executeId);
        redisUtil.set(redisName,JSON.toJSONString(map));
    }

    public void removeCommandByIp(String ip){
        Map<String, String> map = post();
        map.remove(ip);
        redisUtil.set(redisName,JSON.toJSONString(map));
    }
    public void removeCommandByExecuteId(String executeId){
        Map<String, String> map = post();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue().equals(executeId)) {
                map.remove(entry.getKey());
            }
        }
        redisUtil.set(redisName,JSON.toJSONString(map));
    }

    public String getCommandByIp(String ip){
        Map<String, String> map = post();
        return map.get(ip);
    }

    public Map<String, String> getAllCommand(){
        return post();
    }

}
